import 'package:flutter/widgets.dart';

enum OwnerType { receiver, sender }

OwnerType _of(String name) {
  if (name == OwnerType.receiver.toString()) {
    return OwnerType.receiver;
  } else {
    return OwnerType.sender;
  }
}

class ChatMsgModel {
  // Provides id
  final int? id;
  //当新传入消息刷新列表时，避免重建消息小部件
  final GlobalKey key;
  //消息所属
  final OwnerType ownerType;
  //谁
  final String? ownerName;

  //message
  final String content;
  //提供消息创建时间（以毫秒为单位）
  final int createdAt;
  //是否显示创建时间
  bool showCreatedTime = false;

  ChatMsgModel(
      {this.id,
      required this.ownerType,
      this.ownerName,
      required this.content,
      required this.createdAt})
      : key = GlobalKey();

  factory ChatMsgModel.fromJson(Map<String, dynamic> json) => ChatMsgModel(
        id: json["id"],
        content: json["content"],
        createdAt: json["createdAt"],
        ownerType: _of(json["ownerType"]),
        ownerName: json["ownerName"],
      );

  Map<String, dynamic> toJson() => {
        'id': id,
        'content': content,
        'createdAt': createdAt,
        'ownerName': ownerName,
        //数据库存储不支持复合类型
        'ownerType': ownerType.toString(),
      };
}
